﻿<%@ Application Language="C#" %>
<%@ Import Namespace="System.Configuration" %>
<%@ Import Namespace="SudokuState" %>
<script runat="server">

    void Application_Start(object sender, EventArgs e) 
    {
        // Code that runs on application startup

    }
    
    void Application_End(object sender, EventArgs e) 
    {
    }
        
    void Application_Error(object sender, EventArgs e)
    {
        Exception error = Server.GetLastError();
        String message = String.Format("Error occurred: {0}\n{1}", error.Message, error.StackTrace);
        System.Diagnostics.Debug.WriteLine(message);
        // Global handler #1 - redirect all error requests to custom error page
        Response.Redirect(ConfigurationManager.AppSettings["BasePath"]+ "Error.aspx");
    }

    void Session_Start(object sender, EventArgs e) 
    {
        // Global handler #2 - initialize empty puzzle in session
        Session["puzzle"] = SudokuState.ExampleState();
    }

    void Session_End(object sender, EventArgs e) 
    {
        // Code that runs when a session ends. 
        // Note: The Session_End event is raised only when the sessionstate mode
        // is set to InProc in the Web.config file. If session mode is set to StateServer 
        // or SQLServer, the event is not raised.

    }

    protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e)
    {
        // Global handler #3 - store user roles after they authenticate
        if (FormsAuthentication.CookiesSupported == true)
        {
            if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
            {
                try
                {
                    string username = FormsAuthentication.Decrypt(
                        Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
                    string roles = "user";
                    e.User = new System.Security.Principal.GenericPrincipal(
                        new System.Security.Principal.GenericIdentity(username, "Forms"), roles.Split(';'));
                }
                catch (Exception)
                {
                }
            }
        }
    }
       
</script>
